package com.senssun.blesample.util;

public class WIFIUtils {
    public static String convertAsciiToHex(String str) {
        char[] chars = str.toCharArray();
        StringBuffer hex = new StringBuffer();
        for (int i = 0; i < chars.length; i++) {
            hex.append(Integer.toHexString((int) chars[i]));
        }
        return hex.toString();
    }

    public static String convertHexToASCII(String hex) {//
        StringBuilder sb = new StringBuilder();
        StringBuilder temp = new StringBuilder();
        //49204c6f7665204a617661 split into two characters 49, 20, 4c...
        for (int i = 0; i < hex.length() - 1; i += 2) {
            //grab the hex in pairs
            String output = hex.substring(i, (i + 2));
            //convert hex to decimal
            int decimal = Integer.parseInt(output, 16);
            //convert the decimal to character
            sb.append((char) decimal);
            temp.append(decimal);
        }
        return sb.toString();
    }

    public static String buildCommand(String funCode, String dataCode) {
        StringBuffer sb = new StringBuffer();
        sb.append("100000c5");
        int length = (dataCode.length() + sb.length() + funCode.length() + 4) / 2;
        String len = Integer.toHexString(length);
        if (len.length() == 1) {
            len = "0" + len;
        }
        String checkCode = Integer.toHexString(getHexValue(len + funCode + dataCode) & 0xFF);
        int s = 222;
        int yyy = s & 0xFF;
        sb.append(len);
        sb.append(funCode);
        sb.append(dataCode);
        sb.append(checkCode);
        return sb.toString();
    }

    public static int getHexValue(String str) {
        int sum = 0;
        for (int i = 0; i < str.length(); i += 2) {
            sum = sum + Integer.valueOf(str.substring(i, i + 2), 16);
        }
        return sum;
    }
}
